﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using Com.Alipay;

namespace SuuntoWebsite.Events._201205
{
    public partial class Pay : System.Web.UI.Page
    {
        #region 变量
        protected string city = string.Empty;
        protected string address = string.Empty;
        protected string userName = string.Empty;
        protected string product = string.Empty;
        protected string proEnName = string.Empty;
        protected string proName = string.Empty;
        protected string paymoney = string.Empty;
        protected static string sqlCon = System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionString_Event"].ConnectionString;
        protected string orderId = string.Empty;
        protected string proDescription = string.Empty;
        protected string rewrite = System.Configuration.ConfigurationManager.AppSettings["rewriteType"];
        #endregion

        protected void Page_Load(object sender, EventArgs e)
        {
            if (SetValue())
            {
                BindInfo();
            }
            else
            {
                Response.Redirect("./registration"+rewrite);
            }
        }
        /// <summary>
        /// 设置变量
        /// </summary>
        /// <returns></returns>
        protected bool SetValue()
        {
            bool flag = true;
            try
            {
                userName = Public.Cookie.UserName;
                city = Public.Cookie.StoreId;
                product = Public.Cookie.ProductId;
                paymoney = string.Format("{0:N}", Convert.ToDouble(System.Configuration.ConfigurationManager.AppSettings["paymoney"]));
            }
            catch (Exception ex) { flag = false; }
            if (userName == "0") flag = false;
            return flag;
        }
        /// <summary>
        /// 绑定数据
        /// </summary>
        protected void BindInfo()
        {
            //获取商品信息
            DataTable proInfo = new Bll.EventForSuunto.BLLSuunto_Products().SuuntoProductInfo(sqlCon, Convert.ToInt32(product));
            if (proInfo.Rows.Count == 1)
            {
                product = proInfo.Rows[0]["P_Type"].ToString();
                proName = proInfo.Rows[0]["P_Name"].ToString();
                proEnName = proInfo.Rows[0]["P_EnName"].ToString();
                proDescription = proInfo.Rows[0]["P_Description"].ToString();
                proInfo.Dispose();
            }
            //获取商店信息
            DataTable addressInfo = new Bll.EventForSuunto.BLLSuunto_Store().SuuntoStoreInfo(sqlCon, Convert.ToInt32(city));
            if (addressInfo.Rows.Count > 0)
            {
                city = addressInfo.Rows[0]["S_City"].ToString();
                address = addressInfo.Rows[0]["S_Address"].ToString();
                addressInfo.Dispose();
            }
        }
        /// <summary>
        /// 支付
        /// </summary>
        /// <param name="obj"></param>
        /// <param name="e"></param>
        protected void Btn_Click(object obj, EventArgs e)
        {
            //订单实体
            Model.ModelEvent.ModelSuunto_Order model = new Model.ModelEvent.ModelSuunto_Order();
            model.PKID = new Bll.EventForSuunto.BLLSuunto_Order().GetOrderID(sqlCon);
            model.UID = Public.Cookie.UserId;
            model.PID = Convert.ToInt32(Public.Cookie.ProductId);
            model.Money = Convert.ToDouble(paymoney);
            model.TakeAddress = Convert.ToInt32(Public.Cookie.StoreId);
            model.Count = 1;
            model.KeyCode = DateTime.Now.ToString("yyyyMMdd") + model.PKID.Substring(17, 3);
            model.State = "未付款";
            //保存订单
            bool flag = new Bll.EventForSuunto.BLLSuunto_Order().SuuntoOrderInsert(sqlCon, model);
            //保存成功调取支付宝方法
            if (flag) AlipayFun(model);
        }
        /// <summary>
        /// 支付宝方法
        /// </summary>
        /// <param name="model"></param>
        protected void AlipayFun(Model.ModelEvent.ModelSuunto_Order model)
        {

            #region 担保交易
            ////////////////////////////////////////////请求参数////////////////////////////////////////////

            //必填参数//

            string out_trade_no = model.PKID;  //请与贵网站订单系统中的唯一订单号匹配
            string subject = proEnName + " " + proName;                  //订单名称，显示在支付宝收银台里的“商品名称”里，显示在支付宝的交易管理的“商品名称”的列表里。
            string body = proDescription;                          //订单描述、订单详细、订单备注，显示在支付宝收银台里的“商品描述”里
            string price = string.Format("{0:N}", model.Money);  		        //订单总金额，显示在支付宝收银台里的“商品单价”里

            string logistics_fee = "0.00";                  				//物流费用，即运费。
            string logistics_type = "EXPRESS";				                //物流类型，三个值可选：EXPRESS（快递）、POST（平邮）、EMS（EMS）
            string logistics_payment = "SELLER_PAY";            			//物流支付方式，两个值可选：SELLER_PAY（卖家承担运费）、BUYER_PAY（买家承担运费）

            string quantity = "1";              							//商品数量，建议默认为1，不改变值，把一次交易看成是一次下订单而非购买一件商品。

            //选填参数//

            //买家收货信息（推荐作为必填）
            //该功能作用在于买家已经在商户网站的下单流程中填过一次收货信息，而不需要买家在支付宝的付款流程中再次填写收货信息。
            //若要使用该功能，请至少保证receive_name、receive_address有值
            //收货信息格式请严格按照姓名、地址、邮编、电话、手机的格式填写
            DataTable dt = new Bll.EventForSuunto.BLLSuunto_Users().GetUserInfo(sqlCon, Public.Cookie.UserId);
            string receive_name = dt.Rows[0]["S_UserName"].ToString();		                    //收货人姓名，如：张三
            string receive_address = city + " " + address;			                //收货人地址，如：XX省XXX市XXX区XXX路XXX小区XXX栋XXX单元XXX号
            string receive_zip = dt.Rows[0]["S_ZipCode"].ToString();                  			    //收货人邮编，如：123456
            string receive_phone = dt.Rows[0]["S_Tel"].ToString();                		    //收货人电话号码，如：0571-81234567
            string receive_mobile = dt.Rows[0]["S_Phone"].ToString();               		    //收货人手机号码，如：13312341234

            //网站商品的展示地址，不允许加?id=123这类自定义参数
            string show_url = "http://127.0.0.1:8080/Events/201205/selection.html";

            ////////////////////////////////////////////////////////////////////////////////////////////////
            #endregion

            //把请求参数打包成数组
            SortedDictionary<string, string> sParaTemp = new SortedDictionary<string, string>();
            sParaTemp.Add("body", body);
            sParaTemp.Add("logistics_fee", logistics_fee);
            sParaTemp.Add("logistics_payment", logistics_payment);
            sParaTemp.Add("logistics_type", logistics_type);
            sParaTemp.Add("out_trade_no", out_trade_no);
            sParaTemp.Add("payment_type", "1");
            sParaTemp.Add("price", price);
            sParaTemp.Add("quantity", quantity);
            sParaTemp.Add("receive_address", receive_address);
            sParaTemp.Add("receive_mobile", receive_mobile);
            sParaTemp.Add("receive_name", receive_name);
            sParaTemp.Add("receive_phone", receive_phone);
            sParaTemp.Add("receive_zip", receive_zip);
            sParaTemp.Add("show_url", show_url);
            sParaTemp.Add("subject", subject);

            //构造担保交易接口表单提交HTML数据，无需修改
            Service ali = new Service();
            string sHtmlText = ali.Create_partner_trade_by_buyer(sParaTemp);
            Response.Write(sHtmlText);
        }
    }
}
